package com.heze.xunhuan.utils;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.heze.xunhuan.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 微信工具类
 *
 * @author heze-xunhuan
 */
@Slf4j
@Component
public class WechatUtil {

    @Value("${spring.wechat.appid}")
    private String appid;

    @Value("${spring.wechat.secret}")
    private String secret;

    private static final String JSCODE2SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 通过code获取openid和session_key
     *
     * @param code 微信登录code
     * @return JSONObject 包含openid、session_key等
     */
    public JSONObject code2Session(String code) {
        String url = String.format("%s?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                JSCODE2SESSION_URL, appid, secret, code);

        try {
            String response = HttpUtil.get(url);
            JSONObject jsonObject = JSONUtil.parseObj(response);

            if (jsonObject.containsKey("errcode")) {
                Integer errcode = jsonObject.getInt("errcode");
                String errmsg = jsonObject.getStr("errmsg");
                log.error("微信登录失败: errcode={}, errmsg={}", errcode, errmsg);
                throw new BusinessException(400, "微信登录失败");
            }

            return jsonObject;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("调用微信API异常", e);
            throw new BusinessException(500, "调用微信API异常");
        }
    }

    /**
     * 解密手机号（需要前端传入encryptedData和iv）
     * 这里简化处理，实际应该使用AES解密
     */
    public String decryptPhone(String encryptedData, String iv, String sessionKey) {
        // TODO: 实现AES解密逻辑
        // 这里需要根据微信提供的解密算法实现
        throw new UnsupportedOperationException("手机号解密功能待实现");
    }
}